package com.upeoe.shiro.chapter2.permissions;

import com.alibaba.druid.util.StringUtils;
import org.apache.shiro.authz.Permission;

/**
 * @author ven_hxz
 * @create 2016-07-03 下午1:34
 * <p>
 * 规则 : +资源字符串+权限位+实例ID
 * <p>
 * 权限 :
 * 0 所有        0000
 * 1 新增        0001
 * 2 修改        0010
 * 4 删除        0100
 * 8 查看        1000
 * <p>
 * eg   :
 * +user+10 : 对资源user拥有修改/查看权限
 */
public class BitPermission implements Permission {
    private String resourceIdentify;
    private int permissionBit;
    private String instanceId;

    public BitPermission(String permissionString) {
        String[] array = permissionString.split("\\+");

        if (array.length > 1) {
            resourceIdentify = array[1];
        }

        if (StringUtils.isEmpty(resourceIdentify)) {
            resourceIdentify = "*";
        }

        if (array.length > 2) {
            permissionBit = Integer.parseInt(array[2]);
        }

        if (array.length > 3) {
            instanceId = array[3];
        }

        if (StringUtils.isEmpty(instanceId)) {
            instanceId = "*";
        }
    }

    public boolean implies(org.apache.shiro.authz.Permission p) {
        if (!(p instanceof BitPermission)) {
            return false;
        }

        BitPermission other = (BitPermission) p;
        if (!("*".equals(this.resourceIdentify) ||
                this.resourceIdentify.equals(other.resourceIdentify))) {
            return false;
        }

        if (!(this.permissionBit == 0 || (this.permissionBit & other.permissionBit) != 0)) {
            return false;
        }

        if (!("*".equals(this.instanceId) || this.instanceId.equals(other.instanceId))) {
            return false;
        }

        return true;
    }

    @Override
    public String toString() {
        return "BitPermission{" +
                "resourceIdentify='" + resourceIdentify + '\'' +
                ", permissionBit=" + permissionBit +
                ", instanceId='" + instanceId + '\'' +
                '}';
    }
}
